package other;

import java.io.*;
import java.util.regex.Pattern;

/**
 * description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2022/3/9
 */

public class TransformYar {
    public static void main(String[] args) {
        String path = "E:\\home\\tar";
        File tarPath = new File(path);
        if(!tarPath.exists()) {
            tarPath.mkdirs();
        }

        File inDir = new File("E:\\home\\src");
        if(!inDir.isDirectory()) {
            System.out.println("源不是一个目录");
            return;
        }

        Pattern pattern = Pattern.compile("^rule ");
        StringBuilder builder = new StringBuilder();
        String line, preLine;
        for(File file : inDir.listFiles()) {
            String out = path + File.separator + file.getName();
            try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(out)))) {
                preLine = "";
                builder.setLength(0);

                while ((line = reader.readLine()) != null) {
                    if("}".equals(line.trim())) {
                        continue;
                    }

                    if(pattern.matcher(line).find()) {
                        if(preLine.trim().length() != 0) {
                            writer.write(format(preLine.replace("\"", "")) + "\n");
                        }

                        builder.setLength(0);
                        builder.append(line);
                    } else {
                        builder.append(" ").append(line.trim());
                    }
                    preLine = builder.toString();
                }

                writer.write(format(preLine.replace("\"", "")) + "\n");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static String format(String line) {
        String[] delimiter = new String[] {"{ meta: author=", "date=", "hash=", "src=", "virus_name=", "strings:", "condition:"};
        int startPos = 5;
        int endPos;
        StringBuilder builder = new StringBuilder();
        for (int idx = 0; idx < delimiter.length; ++idx) {
            endPos = line.indexOf(delimiter[idx]);
            builder.append(idx == 0 ? "" : "<--->").append(line.substring(startPos, endPos).trim());
            startPos = endPos + delimiter[idx].length();
        }
        builder.append("<--->").append(line.substring(startPos).trim());
        return builder.toString();
    }
}
